package it.fuesi.synoutils.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import it.fuesi.synoutils.R;
import it.fuesi.synoutils.activities.MainActivity;
import it.fuesi.synoutils.adapters.EmuleSearchAdapter;
import it.fuesi.synoutils.model.download.DownloadStationClientParameters;
import it.fuesi.synoutils.model.emulesearch.EmuleSearchResultItem;
import it.fuesi.synoutils.services.tasks.download.CreateEmuleDownloadTask;


/**
 * A simple {@link android.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link it.fuesi.synoutils.fragments.EmuleSearchFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link it.fuesi.synoutils.fragments.EmuleSearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class EmuleSearchFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SECTION_NUMBER = "section_number";
    private static final String ARG_SEARCH_KEYWORD = "KEYWORD";
    private static final String TAG = "SearchFragment";


    // TODO: Rename and change types of parameters
    private int mSectionNumber;

    private OnFragmentInteractionListener mListener;

    private ListView mSearchResults;
    private EmuleSearchAdapter mAdapter;
    private EditText mSearchInput;
    private ImageButton mBtnSearch;


    @Override
    public void onActionRefresh() {

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     *
     * @return A new instance of fragment DownloadStationFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EmuleSearchFragment newInstance(int position, String keyword) {
        EmuleSearchFragment fragment = new EmuleSearchFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position);
        args.putString(ARG_SEARCH_KEYWORD, keyword);
        fragment.setArguments(args);
        return fragment;
    }

    public static EmuleSearchFragment newInstance(int position) {
        return newInstance(position, null);
    }

    public EmuleSearchFragment() {
        // Required empty public constructor
    }

    private String mSearchKeyword;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
            if(getArguments().containsKey(ARG_SEARCH_KEYWORD))
                mSearchKeyword = getArguments().getString(ARG_SEARCH_KEYWORD);
            else
                mSearchKeyword = null;
        }



    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        final View rootView = inflater.inflate(R.layout.fragment_search, container, false);

        mSearchResults = (ListView)rootView.findViewById(R.id.search_results);

        mAdapter = new EmuleSearchAdapter(inflater,null, this.getActivity(), this);

        mSearchResults.setAdapter(mAdapter);

        mSearchResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                EmuleSearchResultItem result = (EmuleSearchResultItem)mAdapter.getItem(i);
                Log.d(TAG, "Clicked result: " + result.getFileID());
                confirmDownload(result);
            }
        });

        mSearchInput = (EditText)rootView.findViewById(R.id.search_input);

        mBtnSearch = (ImageButton)rootView.findViewById(R.id.btn_search);

        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String keyWord = mSearchInput.getText().toString();
                mAdapter.fetch(keyWord);
            }
        });

        if(mSearchKeyword != null){
            mSearchInput.setText(mSearchKeyword);
            mAdapter.fetch(mSearchKeyword);
        }


        return rootView;
    }

    private void confirmDownload(final EmuleSearchResultItem result){
        new AlertDialog.Builder(getActivity())
                .setTitle("Confirm download")
                .setMessage("Download " + result.getName() + " ?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        download(result.getFileID());
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
    }

    private void download(String fileId){
        final DownloadStationClientParameters params = new DownloadStationClientParameters();
        params.setFileID(fileId);
        params.setForceAuthentication(false);
        new CreateEmuleDownloadTask(getActivity()).execute(params);
    }

    @Override
    public boolean onBackPressed() {
        final MainActivity main = (MainActivity)getActivity();
        main.quit();
        return true;
    }



    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;

        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }

            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }





}
